package com.pvj.myaccount.ui.home

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.pvj.myaccount.repository.HomeRepository
import com.pvj.myaccount.room.DbHelper
import com.pvj.myaccount.room.entity.Cost
import com.pvj.myaccount.room.entity.MonthCost
import com.pvj.myaccount.uitls.TimeUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.Calendar
import java.util.TimeZone

class HomeViewModel : ViewModel() {
    private val repository = HomeRepository()

    private val _costs = MutableLiveData<List<Cost>?>()
    val costs: LiveData<List<Cost>?> = _costs


    fun loadTodayData() {
        val todayStart = TimeUtil.getCurrentDayStartBeijingTimestamp()
        val todayEnd = TimeUtil.getCurrentDayEndBeijingTimestamp()

        viewModelScope.launch {
            val data = repository.getData(todayStart, todayEnd)
            // 更新LiveData
            _costs.postValue(data)
        }
    }

    fun loadMonthData(): List<MonthCost>? {
       return DbHelper.INSTANCE?.monthCostDao()?.getAll()
    }

    fun updateAsync(data: Cost) {
        viewModelScope.launch(Dispatchers.IO) {
            repository.update(data)
        }
    }

    fun insertAsync(data: Cost) {
        viewModelScope.launch(Dispatchers.IO) {
            repository.insert(data)
        }
    }

    fun delete(data: Cost) {
        repository.delete(data)
    }

}